package net.qhzw.vip.qiyu.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import net.qhzw.vip.qiyu.dto.ShopCartDto;
import net.qhzw.vip.qiyu.dto.ShopCartItemDiscountDto;
import net.qhzw.vip.qiyu.dto.ShopCartItemDto;
import net.qhzw.vip.qiyu.entity.*;
import net.qhzw.vip.qiyu.evnet.ShopCartEvent;
import net.qhzw.vip.qiyu.mapper.BasketMapper;
import net.qhzw.vip.qiyu.param.ChangeShopCartParam;
import net.qhzw.vip.qiyu.param.OrderItemParam;
import net.qhzw.vip.qiyu.param.ShopCartParam;
import net.qhzw.vip.qiyu.service.*;
import net.qhzw.vip.qiyu.util.Arith;
import net.qhzw.vip.qiyu.util.CacheManagerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService {


    @Autowired
    private BasketMapper basketMapper;


    @Autowired
    private CacheManagerUtil cacheManagerUtil;


    @Autowired
    private ApplicationContext applicationContext;


    @Autowired
    private SkuService skuService;

    @Autowired
    private ShopDetailService shopDetailService;

    @Autowired
    private ProductService productService;

    @Autowired
    private MallUserVipService mallUserVipService;


    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void deleteShopCartItemsByBasketIds(Long userId, List<Long> basketIds) {
        basketMapper.deleteShopCartItemsByBasketIds(userId, basketIds);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void addShopCartItem(ChangeShopCartParam param, Long userId) {
        Basket basket = new Basket();
        basket.setBasketId(IdWorker.getId());
        basket.setBasketCount(param.getCount());
        basket.setBasketDate(new Date());
        basket.setProdId(param.getProdId());
        basket.setShopId(param.getShopId());
        basket.setUserId(userId);
        basket.setSkuId(param.getSkuId());
        basket.setDistributionCardNo(param.getDistributionCardNo());
        basketMapper.insert(basket);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#basket.userId")
    public void updateShopCartItem(Basket basket) {
        basketMapper.updateById(basket);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void deleteAllShopCartItems(Long userId) {
        basketMapper.deleteAllShopCartItems(userId);
    }

    @Override
    public List<ShopCartItemDto> getShopCartItems(Long userId) {
        // 在这个类里面要调用这里的缓存信息，并没有使用aop，所以不使用注解
        List<ShopCartItemDto> shopCartItemDtoList = cacheManagerUtil.getCache("ShopCartItems", String.valueOf(userId));
        if (!CollectionUtils.isEmpty(shopCartItemDtoList)) {
            for (ShopCartItemDto shopCartItemDto : shopCartItemDtoList) {
                int userVip = mallUserVipService.getVIPbyProdId(userId, shopCartItemDto.getProdId());
                shopCartItemDto.setMallVip(userVip);
                double vipPrice = shopCartItemDto.getVipPrice();
                double price = shopCartItemDto.getPrice();
                if (userVip == 1) {
                    shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), vipPrice));
                } else {
                    shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), price));
                }
            }
            return shopCartItemDtoList;
        }
        if (shopCartItemDtoList != null) {
            // return shopCartItemDtoList;
        }
        shopCartItemDtoList = basketMapper.getShopCartItems(userId);
        if (!CollectionUtils.isEmpty(shopCartItemDtoList)) {
            for (ShopCartItemDto shopCartItemDto : shopCartItemDtoList) {
                int userVip = mallUserVipService.getVIPbyProdId(userId, shopCartItemDto.getProdId());

                double prodPlatform = Arith.add(shopCartItemDto.getPlatformFee(), shopCartItemDto.getSiteFee());

                double vipPrice = Arith.add(shopCartItemDto.getVipPrice(), Arith.add(shopCartItemDto.getVipPrice(), shopCartItemDto.getSiteFee()));



                double price = Arith.add(shopCartItemDto.getPrice(), prodPlatform);

                //shopCartItemDto.setVipPrice(Arith.add(shopCartItemDto.getVipPrice(), Arith.add(shopCartItemDto.getVipPlatformFee(), shopCartItemDto.getSiteFee())));
                shopCartItemDto.setVipPrice(Arith.add(shopCartItemDto.getVipPrice(), shopCartItemDto.getVipPlatformFee()));

                shopCartItemDto.setOriPrice(Arith.add(shopCartItemDto.getOriPrice(), prodPlatform));
                shopCartItemDto.setPrice(Arith.add(shopCartItemDto.getPrice(), prodPlatform));
                shopCartItemDto.setMallVip(userVip);

                if (userVip == 1) {
                    shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), vipPrice));
                } else {
                    shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), price));
                }
            }
        }

        cacheManagerUtil.putCache("ShopCartItems", String.valueOf(userId), shopCartItemDtoList);
        return shopCartItemDtoList;
    }

    @Override
    public List<ShopCartItemDto> getShopCartExpiryItems(Long userId) {
        return basketMapper.getShopCartExpiryItems(userId);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void cleanExpiryProdList(Long userId) {
        basketMapper.cleanExpiryProdList(userId);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void updateBasketByShopCartParam(Long userId, Map<Long, ShopCartParam> basketIdShopCartParamMap) {
        basketMapper.updateDiscountItemId(userId, basketIdShopCartParamMap);
    }

    @Override
    @CacheEvict(cacheNames = "ShopCartItems", key = "#userId")
    public void removeShopCartItemsCacheByUserId(String userId) {

    }

    @Override
    public List<String> listUserIdByProdId(Long prodId) {
        return basketMapper.listUserIdByProdId(prodId);
    }

    @Override
    public List<ShopCartDto> getShopCarts(List<ShopCartItemDto> shopCartItems) {
        // 根据店铺ID划分item
        Map<Long, List<ShopCartItemDto>> shopCartMap = shopCartItems.stream()
                .collect(Collectors.groupingBy(ShopCartItemDto::getShopId));
        // 返回一个店铺的所有信息
        List<ShopCartDto> shopCartDtos = Lists.newArrayList();
        for (Long shopId : shopCartMap.keySet()) {
            //获取店铺的所有商品项
            List<ShopCartItemDto> shopCartItemDtoList = shopCartMap.get(shopId);
            // 构建每个店铺的购物车信息
            ShopCartDto shopCart = new ShopCartDto();
            //店铺信息
            shopCart.setShopId(shopId);
            shopCart.setShopName(shopCartItemDtoList.get(0).getShopName());
            shopCart.setShopCartItemDiscounts(getShopCartItem(shopCartItems));
            applicationContext.publishEvent(new ShopCartEvent(shopCart, shopCartItemDtoList));
            shopCartDtos.add(shopCart);
        }
        return shopCartDtos;
    }

    private List<ShopCartItemDiscountDto> getShopCartItem(List<ShopCartItemDto> shopCartItems) {
        ShopCartItemDiscountDto shopCartItemDiscountDto = new ShopCartItemDiscountDto();
        shopCartItemDiscountDto.setShopCartItems(shopCartItems);
        return Arrays.asList(shopCartItemDiscountDto);
    }

    @Override
    public List<ShopCartItemDto> getShopCartItemsByOrderItems(List<Long> basketId, OrderItemParam orderItem, Long userId) {
        //int userVip = basketMapper.isUserVip(userId);

        if (orderItem == null && CollectionUtil.isEmpty(basketId)) {
            return Collections.emptyList();
        }
        // 当立即购买时，没有提交的订单是没有购物车信息的
        if (CollectionUtil.isEmpty(basketId) && orderItem != null) {
            Sku sku = skuService.getSkuBySkuId(orderItem.getSkuId());
            if (sku == null) {
                throw new RuntimeException("订单包含无法识别的商品");
            }
            Product prod = productService.getProductByProdId(orderItem.getProdId());
            if (prod == null) {
                throw new RuntimeException("订单包含无法识别的商品");
            }
            // 拿到购物车的所有item
            ShopCartItemDto shopCartItemDto = new ShopCartItemDto();
            shopCartItemDto.setBasketId(-1L);
            shopCartItemDto.setSkuId(orderItem.getSkuId());
            shopCartItemDto.setProdCount(orderItem.getProdCount());
            shopCartItemDto.setProdId(orderItem.getProdId());
            shopCartItemDto.setSkuName(sku.getSkuName());
            shopCartItemDto.setPic(StrUtil.isBlank(sku.getPic()) ? prod.getPic() : sku.getPic());
            shopCartItemDto.setProdName(sku.getProdName());

            double sukPlatform = Arith.add(sku.getPlatformFee(), prod.getSiteFee());

            int userVip = mallUserVipService.selectUserVip(userId, prod.getShopId());
            if (userVip == 1) {
                double vipPrice = Arith.mul(sku.getVipPrice(), orderItem.getProdCount());
                //shopCartItemDto.setProductTotalAmount(Arith.add(vipPrice, Arith.add(sku.getVipPlatformFee(), prod.getSiteFee())));
                shopCartItemDto.setProductTotalAmount(Arith.add(vipPrice, sku.getVipPlatformFee()));
            } else {
                double price = Arith.mul(sku.getPrice(), orderItem.getProdCount());
                shopCartItemDto.setProductTotalAmount(Arith.add(price, sukPlatform));
            }

            shopCartItemDto.setPrice(Arith.add(sku.getPrice(), sukPlatform));
            shopCartItemDto.setOriPrice(Arith.add(sku.getOriPrice(), sukPlatform));

            //shopCartItemDto.setVipPrice(Arith.add(sku.getVipPrice(), Arith.add(sku.getVipPlatformFee(), prod.getSiteFee())));
            shopCartItemDto.setVipPrice(Arith.add(sku.getVipPrice(), sku.getVipPlatformFee()));

            shopCartItemDto.setDistributionCardNo(orderItem.getDistributionCardNo());
            shopCartItemDto.setBasketDate(new Date());
            shopCartItemDto.setMallVip(userVip);

            shopCartItemDto.setShopId(prod.getShopId());
            Shop shopDetail = shopDetailService.getShopDetailByShopId(prod.getShopId());
            if (shopDetail != null) {
                shopCartItemDto.setShopName(shopDetail.getShopName());
            }
            return Collections.singletonList(shopCartItemDto);
        }
        List<ShopCartItemDto> dbShopCartItems = getShopCartItems(userId);
        // 返回购物车选择的商品信息
        return dbShopCartItems
                .stream()
                .filter(shopCartItemDto -> basketId.contains(shopCartItemDto.getBasketId()))
                .collect(Collectors.toList());
    }


}
